<?php

class Book_IndexController extends Core_Controller_Action_Standard {

    public function indexAction() {

        //menu
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('book_main');

        //table books 
        $bookTb = Engine_Api::_()->getDbTable('books', 'book');

        //select book to display
        $select = $bookTb->select();

        //phan trang
        $this->view->books = $books = Zend_Paginator::factory($select);
        $page = $this->_getParam('page', 1);
        $books->setItemCountPerPage(10);
        $books->setCurrentPageNumber($page);

        //set subject to display widget
        $book2 = Engine_Api::_()->getItem('book', $this->_getParam('book_id'));
        if ($book2) {
            Engine_Api::_()->core()->setSubject($book2);
        }

        //show widget
        $this->_helper->content
                //->setNoRender()
                ->setEnabled()
        ;

        //id viewer===========================================================
//        $viewer = Engine_Api::_()->user()->getViewer();
//        $this->view->id = $viewer->getIdentity();
//==============================================================================
        //send mail
        //user
//        $user = $viewer;
        //mail type
//        $mailType = 'core_welcome_password';
        //mail param
//        $mailParams = array(
//            'host' => $_SERVER['HTTP_HOST'],
//            'email' => $user->email,
//            'password' => $password,
//            'date' => time(),
//            'recipient_title' => $user->getTitle(),
//            'recipient_link' => $user->getHref(),
//            'recipient_photo' => $user->getPhotoUrl('thumb.icon'),
//            'object_link' => ( _ENGINE_SSL ? 'https://' : 'http://' )
//            . $_SERVER['HTTP_HOST']
//            . Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true),
//        );
        //send
//        Engine_Api::_()->getApi('mail', 'core')->sendSystem(
//                $user, $mailType, $mailParams
//        );
//==============================================================================
        //get field
//        $fields = Engine_Api::_()->fields()->getFieldsValuesByAlias($viewer);
//        var_dump($fields['birthdate']);
//        var_dump($fields);
//        die;
//==============================================================================
        //log
//        $writer = new Zend_Log_Writer_Stream('php://output');
//        $logger = new Zend_Log($writer);
//        $logger->info('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
    }

    public function addAction() {

        //Permissions
        if (!$this->_helper->requireAuth()->setAuthParams('book', null, 'create')->isValid()) {
            return;
        }


        //form
        $form = new Book_Form_Create();
        $form->agree->setLabel('Add');
        $this->view->form = $form;

        //menu
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('book_main');

        //get current user
        $viewer = Engine_Api::_()->user()->getViewer();
        $owner = $viewer->getIdentity();

        //====================================add book
//        if ($owner == 0) {
//            $this->_helper->redirector->gotoRoute(array('action' => 'index'));
//        } else {
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {

                //get value
                $title = $form->getValue('title');
                $author = $form->getValue('author');
                $description = $form->getValue('description');
                $price = $form->getValue('price');

                //image
                $upload = new Zend_File_Transfer();
                $upload->setDestination(APPLICATION_PATH_PUB . DS . 'PictureBook');

                $name = "avatar.jpg";
                if ($upload->receive()) {
                    $name = $form->getValue('image');
                }

                //add into database
                //table books
                $bookTb = Engine_Api::_()->getDbTable('books', 'book');

                ////create row
                $book = $bookTb->createRow();

                ////input values
                $book->title = $title;
                $book->author = $author;
                $book->description = $description;
                $book->price = $price;
                $book->owner_id = $owner;
                $book->image = $name;

                ////save table
                $book->save();

                // Auth
                $viewer = Engine_Api::_()->user()->getViewer();
                $values = array_merge($form->getValues(), array(
                    'owner_type' => $viewer->getType(),
                    'owner_id' => $viewer->getIdentity(),
                ));

                $auth = Engine_Api::_()->authorization()->context;
                $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

                if (empty($values['auth_view'])) {
                    $values['auth_view'] = 'everyone';
                }

                if (empty($values['auth_comment'])) {
                    $values['auth_comment'] = 'everyone';
                }

                $viewMax = array_search($values['auth_view'], $roles);
                $commentMax = array_search($values['auth_comment'], $roles);

                foreach ($roles as $i => $role) {
                    $auth->setAllowed($book, $role, 'view', ($i <= $viewMax));
                    $auth->setAllowed($book, $role, 'comment', ($i <= $commentMax));
                }

                //feed action
                $api = Engine_Api::_()->getDbtable('actions', 'activity');
                $action = $api->addActivity($viewer, $book, 'book_new');

                //attach image book    
////////////////////////////////////////////////
                //$api->attachActivity($action, $book, Activity_Model_Action::ATTACH_MULTI);
                $api->attachActivity($action, $book);

                //$this->_redirect('book/index/mybook');
                $this->_helper->redirector->gotoRoute(array('action' => 'mybook'));
            }
        }
    }

    public function mybookAction() {
        //menu
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('book_main');

        //table books 
        $bookTb = Engine_Api::_()->getDbTable('books', 'book');

        //owner id
        $viewer = Engine_Api::_()->user()->getViewer();
        $owner = $viewer->getIdentity();

        //select book to display
        $select = $bookTb->select();
        $select->where('owner_id = ?', $owner);

        //phan trang
        $this->view->books = $books = Zend_Paginator::factory($select);
        $page = $this->_getParam('page', 1);
        $books->setItemCountPerPage(10);
        $books->setCurrentPageNumber($page);
    }

    public function editAction() {

        //get book id
        $book_id = $this->_getParam("book_id");

        //get current book and view
        $bookTb = Engine_Api::_()->getDbTable('books', 'book');
        $select = $bookTb->select();
        $select->where('book_id = ?', $book_id);
        $book = $bookTb->fetchRow($select);

        //Permissions
        if (!$this->_helper->requireAuth()->setAuthParams($book, null, 'edit')->isValid()) {
            return;
        }

        //form
        $form = new Book_Form_Create();

        //show info book 
        $form->agree->setLabel('Edit');
        $form->title->setValue($book->title);
        $form->author->setValue($book->author);
        $form->description->setValue($book->description);
        $form->price->setValue($book->price);
        $this->view->form = $form;

        //menu
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('book_main');

        //edit book
        $submit = $this->_getParam('agree');
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $book->title = $title = $this->_getParam('title');
                $book->author = $author = $this->_getParam('author');
                $book->description = $description = $this->_getParam('description');
                $book->price = $price = $this->_getParam('price');

                //image
                $upload = new Zend_File_Transfer();
                //$upload->setDestination('F:\wamp\www\se483\public\PictureBook');
                $upload->setDestination(APPLICATION_PATH_PUB . DS . 'PictureBook');
                if ($upload->receive()) {
                    $name_image = $upload->getFileName();
                    $array = explode('\\', $name_image);
                    $i = count($array);
                    $name = $array[$i - 1];
                    $book->image = $name;
                }

                $book->save();


                // Auth
                $viewer = Engine_Api::_()->user()->getViewer();
                $values = array_merge($form->getValues(), array(
                    'owner_type' => $viewer->getType(),
                    'owner_id' => $viewer->getIdentity(),
                ));

                $auth = Engine_Api::_()->authorization()->context;
                $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

                if (empty($values['auth_view'])) {
                    $values['auth_view'] = 'everyone';
                }

                if (empty($values['auth_comment'])) {
                    $values['auth_comment'] = 'everyone';
                }

                $viewMax = array_search($values['auth_view'], $roles);
                $commentMax = array_search($values['auth_comment'], $roles);

                foreach ($roles as $i => $role) {
                    $auth->setAllowed($book, $role, 'view', ($i <= $viewMax));
                    $auth->setAllowed($book, $role, 'comment', ($i <= $commentMax));
                }

                //$this->_helper->redirector->gotoRoute(array('action' => 'mybook'));
                //$this->_redirect('book/index/mybook');
                $this->_helper->redirector->gotoRoute(array('action' => 'mybook'));
            }
        }
    }

    public function deleteAction() {



        //form
        $form = new Book_Form_Delete();
        $this->view->form = $form;

        //menu
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('book_main');

        //get book id
        $book_id = $this->_getParam("book_id");

        //get current book
        $bookTb = Engine_Api::_()->getDbTable('books', 'book');
        $book = $bookTb->findRow($book_id);
        $this->view->book = $book;

        $delete = $this->_getParam('delete');
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $book->delete();
                //$this->_redirect('book/index/index');
                $this->_helper->redirector->gotoRoute(array('action' => 'mybook'));
            }
        }

        //Permissions
        if (!$this->_helper->requireAuth()->setAuthParams($book, null, 'delete')->isValid()) {
            return;
        }
    }

    public function detailbookAction() {

        $book_id = $this->_getParam('book_id');
        $bookTb = Engine_Api::_()->getDbTable('books', 'book');
        $book = $bookTb->findRow($book_id);
        $this->view->book = $book;

        //view count
        $book->view_count++;
        $book->save();

        //from button cancel
        $form = new Engine_Form();
        $cancel = $form->addElement('cancel', 'cancel', array(
            'label' => 'Exit'
        ));
        $this->view->cancel = $cancel;

        //set subject to display widget
        $book2 = Engine_Api::_()->getItem('book', $this->_getParam('book_id'));
        if ($book2) {
            Engine_Api::_()->core()->setSubject($book2);
        }

        //show widget
        $this->_helper->content
                //->setNoRender()
                ->setEnabled()
        ;
    }

}
